#include "NFRebotModule.h"

bool NFRebotModule::Init()
{
    m_pNoSqlModule = pPluginManager->FindModule<NFINoSqlModule>();
    return true;
}

uint32_t NFRebotModule::GetStaticRebotId()
{
    std::string strAccountKey = "NFRebot";
    NF_SHARE_PTR<NFINoSqlDriver> xNoSqlDriver = m_pNoSqlModule->GetDriverBySuitRandom();
    if (xNoSqlDriver)
    {
        if (!xNoSqlDriver->Exists(strAccountKey))
        {
            xNoSqlDriver->Set(strAccountKey, lexical_cast<std::string>(NFRebot::m_staticRebotId));
            return NFRebot::m_staticRebotId;
        }
        else
        {
            std::string rebotStrId;
            xNoSqlDriver->Get(strAccountKey, rebotStrId);
            NFRebot::m_staticRebotId = lexical_cast<int>(rebotStrId);
            NFRebot::m_staticRebotId++;
            xNoSqlDriver->Set(strAccountKey, lexical_cast<std::string>(NFRebot::m_staticRebotId));
            return NFRebot::m_staticRebotId;
        }
    }
    return 0;
}

bool NFRebotModule::AfterInit()
{
    return true;
}

bool NFRebotModule::ReadyExecute()
{
    return true;
}

bool NFRebotModule::Execute()
{
    if (m_mapRebots.Count() >= 5)
    {
        return true;
    }

    static uint64_t lastTime = 0;

    if (NFGetTime() - lastTime <= 1000)
    {
        return true;
    }

    lastTime = NFGetTime();

    for (int i = 0; i < 1; i++)
    {
        uint32_t rebotId = GetStaticRebotId();
        NF_SHARE_PTR<NFRebot> pRebot = NF_SHARE_PTR<NFRebot>(NF_NEW NFRebot(pPluginManager, rebotId));
        if (pRebot)
        {
            pRebot->Init();
            pRebot->AfterInit();
            m_mapRebots.AddElement(pRebot->m_rebotServerId, pRebot);
        }
    }
    return true;
}